package pingan.com.imandtwo.fragments.addressbookfragment;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import pingan.com.imandtwo.R;
import pingan.com.imandtwo.fragments.addressbookfragment.tongxunl.ContactVo;
import pingan.com.imandtwo.fragments.addressbookfragment.tongxunl.MyAdapter;
import pingan.com.imandtwo.interfaces.Iview;
import pingan.com.imandtwo.presenter.HttpPresenter;

/**
 * Created by 迷人的脚毛！！ on 2018/2/6.
 */

public class ModileFragment extends Fragment implements Iview{
    /** 获取库Phone表字段 **/
    private static final String[] PHONES_PROJECTION = new String[] {
            Phone.DISPLAY_NAME, Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, Phone.CONTACT_ID };
    /** 联系人显示名称 **/
    private static final int PHONES_DISPLAY_NAME = 0;

    /** 电话号码 **/
    private static final int PHONES_NUMBER = 1;

    /** 头像ID **/
    private static final int PHONES_PHOTO_ID = 2;

    /** 联系人的ID **/
    private static final int PHONES_CONTACT_ID = 3;

    private static final String TAG = "ModileFragment";
    private MyAdapter mAdapter;
    private ListView listview;
    private Button btn;
    private List<ContactVo> lists=new ArrayList<ContactVo>();
    private HttpPresenter presenter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.modile_fragment, container, false);
        listview = (ListView)view.findViewById(R.id.listview);

        getPhoneContacts();

        presenter = new HttpPresenter(this);

        return view;
    }

    private void getPhoneContacts() {
        // rely=(RelativeLayout) findViewById(R.id.relationId);
        ContentResolver resolver = getActivity().getContentResolver();
        List<ContactVo> list=new ArrayList<ContactVo>();
        // 获取手机联系人
        Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
                PHONES_PROJECTION, null, null, null);

        // 不为空
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                ContactVo cv=new ContactVo();
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;

                // 得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME);

                // 得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID);
                // 得到联系人头像ID
                Long imgid = phoneCursor.getLong(PHONES_PHOTO_ID);

                // 得到联系人头像Bitamp
                Bitmap contactPhoto = null;

                // photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
                if (imgid > 0) {
                    Uri uri = ContentUris.withAppendedId(
                            ContactsContract.Contacts.CONTENT_URI, contactid);
                    InputStream input = ContactsContract.Contacts
                            .openContactPhotoInputStream(resolver, uri);
                    contactPhoto = BitmapFactory.decodeStream(input);
                } else {
                    contactPhoto = BitmapFactory.decodeResource(getResources(),
                            R.mipmap.ic_launcher);
                }

                cv.setName(contactName);
                //Log.i("info", "1111111"+contactName);
                cv.setMoble(phoneNumber);
                cv.setImg(contactPhoto);
                //Log.i("info", "img----"+contactPhoto);
                list.add(cv);
            }
            phoneCursor.close();
            lists.clear();
            lists.addAll(list);
            // Log.i("info", "lists----"+lists);
        }
        mAdapter=new MyAdapter(getActivity(), lists);
        listview.setAdapter(mAdapter);

        mAdapter.setOnRecycleViewListener(new MyAdapter.OnRecycleViewListener() {
            @Override
            public void onItemClick(final int postion) {
                final EditText editText = new EditText(getActivity());
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("添加好友界面");
                builder.setView(editText);
                builder.setMessage("你是谁？");
                builder.setPositiveButton("添加",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                HashMap<String, String> map = new HashMap<>();
                                presenter.getMap(map,"添加好友");
//                                    EMClient.getInstance().contactManager().addContact(lists.get(postion).getMoble()+"", editText.getText().toString());

                                    Toast.makeText(getActivity(),"发送添加消息:"+lists.get(postion).getMoble(),Toast.LENGTH_SHORT).show();
                            }
                        });
                builder.show();
            }
        });
    }

    @Override
    public void onSuccess(Object o, String tag) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.disAttach();
    }
}
